package com.che.software.testato.web.controller;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ActionEvent;
import javax.faces.model.SelectItem;

import org.apache.log4j.Logger;
import org.primefaces.context.RequestContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.che.software.testato.business.ServiceManager;
import com.che.software.testato.business.UserManager;
import com.che.software.testato.business.exception.ServiceSearchManagerException;
import com.che.software.testato.business.exception.UserCreationManagerException;
import com.che.software.testato.business.exception.UserSearchManagerException;
import com.che.software.testato.domain.entity.Service;
import com.che.software.testato.domain.entity.User;
import com.che.software.testato.domain.entity.creation.UserCreation;
import com.che.software.testato.domain.entity.search.ServiceSearch;
import com.che.software.testato.domain.entity.search.UserSearch;
import com.che.software.testato.web.controller.acontroller.AbstractController;

/**
 * Controller used to manage the users and their rights administration.
 * 
 * @author Clement HELIOU (clement.heliou@che-software.com).
 * @copyright Che Software.
 * @license GNU General Public License.
 * @see AbstractController, Serializable.
 * @since July, 2011.
 * 
 *        This file is part of Testato.
 * 
 *        Testato is free software: you can redistribute it and/or modify it
 *        under the terms of the GNU General Public License as published by the
 *        Free Software Foundation, either version 3 of the License, or (at your
 *        option) any later version.
 * 
 *        Testato is distributed in the hope that it will be useful, but WITHOUT
 *        ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 *        FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 *        for more details.
 * 
 *        You should have received a copy of the GNU General Public License
 *        along with Testato. If not, see <http://www.gnu.org/licenses/>.
 * 
 *        Testato's logo is a creation of Arrioch
 *        (http://arrioch.deviantart.com/) and it's distributed under the terms
 *        of the Creative Commons License.
 */
@Component("usersAdministrationController")
@ManagedBean(name = "usersAdministrationController")
@Scope("session")
@SessionScoped
public class UsersAdministrationController extends AbstractController implements Serializable {

	/**
	 * Constants.
	 */
	private static final Logger LOGGER = Logger.getLogger(UsersAdministrationController.class);
	private static final long serialVersionUID = 7261995396159429390L;

	/**
	 * Members.
	 */
	private List<User> users;
	private List<SelectItem> servicesList;
	@Autowired
	private transient ServiceManager serviceManager;
	private UserCreation userToCreate;
	private User[] selectedUsers;
	@Autowired
	private transient UserManager userManager;

	/**
	 * Creating the object corresponding to the user to create.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @param ev the event launched during the creation of a user.
	 * @since July, 2011.
	 */
	public void createUser(ActionEvent ev) {
		LOGGER.debug("createUser(" + userToCreate.getLogin() + ").");
		try {
			userManager.createUserFromBean(userToCreate);
			userToCreate = new UserCreation();
			users = null; // To trigger the data loading.
			RequestContext.getCurrentInstance().addPartialUpdateTarget("usersForm:usersTable");
		} catch (UserCreationManagerException e) {
			LOGGER.error("Error during the user creation.", e);
			RequestContext.getCurrentInstance().addCallbackParam(NOT_VALID_CALLBACK_PARAM, true);
		}
	}

	/**
	 * Initializes the object corresponding to the user to create.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @param e the event launched during the creation of an user.
	 * @since July, 2011.
	 */
	public void initUserToCreate(ActionEvent e) {
		LOGGER.debug("initUserToCreate().");
		userToCreate = new UserCreation();
	}

	/**
	 * Redirection to perform to get the users page.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @return the resulting redirection.
	 * @since August, 2011.
	 */
	public String onAccess() {
		LOGGER.debug("onAccess().");
		users = null; // To trigger the data loading.
		selectedUsers = null;
		servicesList = null;
		return "users.xhtml?faces-redirect=true";
	}

	/**
	 * Getter for the private field value userManager.
	 * 
	 * @return the userManager field value.
	 */
	public UserManager getUserManager() {
		return userManager;
	}

	/**
	 * Setting a value to the userManager field.
	 * 
	 * @param userManager the value to set.
	 */
	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

	/**
	 * Getter for the private field value users.
	 * 
	 * @return the users field value.
	 */
	public List<User> getUsers() {
		if (null == users) {
			LOGGER.debug("getUsers(): initialization.");
			try {
				users = userManager.searchUsers(new UserSearch());
			} catch (UserSearchManagerException e) {
				LOGGER.error("Error during the recovery of the users list.", e);
			}
		}
		return users;
	}

	/**
	 * Setting a value to the users field.
	 * 
	 * @param users the value to set.
	 */
	public void setUsers(List<User> users) {
		this.users = users;
	}

	/**
	 * Getter for the private field value selectedUsers.
	 * 
	 * @return the selectedUsers field value.
	 */
	public User[] getSelectedUsers() {
		return selectedUsers;
	}

	/**
	 * Setting a value to the selectedUsers field.
	 * 
	 * @param selectedUsers the value to set.
	 */
	public void setSelectedUsers(User[] selectedUsers) {
		this.selectedUsers = selectedUsers;
	}

	/**
	 * Getter for the private field value userToCreate.
	 * 
	 * @return the userToCreate field value.
	 */
	public UserCreation getUserToCreate() {
		return userToCreate;
	}

	/**
	 * Setting a value to the userToCreate field.
	 * 
	 * @param userToCreate the value to set.
	 */
	public void setUserToCreate(UserCreation userToCreate) {
		this.userToCreate = userToCreate;
	}

	/**
	 * Getter for the private field value serviceManager.
	 * 
	 * @return the serviceManager field value.
	 */
	public ServiceManager getServiceManager() {
		return serviceManager;
	}

	/**
	 * Setting a value to the serviceManager field.
	 * 
	 * @param serviceManager the value to set.
	 */
	public void setServiceManager(ServiceManager serviceManager) {
		this.serviceManager = serviceManager;
	}

	/**
	 * Getter for the private field value servicesList.
	 * 
	 * @return the servicesList field value.
	 */
	public List<SelectItem> getServicesList() {
		if (null == servicesList) {
			LOGGER.debug("getServicesList(): initialization.");
			List<SelectItem> temporaryList = new ArrayList<SelectItem>();
			try {
				for (Service service : serviceManager.searchService(new ServiceSearch())) {
					temporaryList.add(new SelectItem(service.getServiceId(), service.getLabel()));
				}
				servicesList = temporaryList;
			} catch (ServiceSearchManagerException e) {
				LOGGER.error("Error during the services search.", e);
			}
		}
		return servicesList;
	}

	/**
	 * Setting a value to the servicesList field.
	 * 
	 * @param servicesList the value to set.
	 */
	public void setServicesList(List<SelectItem> servicesList) {
		this.servicesList = servicesList;
	}
}